﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

namespace IMES.Common.Services
{
	/// <summary>
	/// RabbitMQ服务
	/// </summary>
	public class RabbitMQService
	{
		private readonly ConnectionFactory _factory;
		/// <summary>
		/// 构造函数
		/// </summary>
		public RabbitMQService()
		{
			_factory = new ConnectionFactory()
			{
				HostName = "123.56.251.87",
				Port = 5672,
				UserName = "admin",
				Password = "X1234567",

			};
		}
		/// <summary>
		/// 发送消息
		/// </summary>
		/// <param name="message"></param>
		public void SendMessage(string message)
		{
			using (var connection = _factory.CreateConnection())
			using (var channel = connection.CreateModel())
			{
				channel.QueueDeclare(queue: "cap.queue.keep.api.v1",
									 durable: false,
									 exclusive: false,
									 autoDelete: false,
									 arguments: null);

				var body = Encoding.UTF8.GetBytes(message);

				channel.BasicPublish(exchange: "",
									 routingKey: "cap.queue.keep.api.v1",
									 basicProperties: null,
									 body: body);
				Console.WriteLine(" [x] Sent {0}", message);
			}
		}
		/// <summary>
		/// 接收消息
		/// </summary>
		public void ReceiveMessages()
		{
			using (var connection = _factory.CreateConnection())
			using (var channel = connection.CreateModel())
			{
				channel.QueueDeclare(queue: "cap.queue.keep.api.v1",
									 durable: false,
									 exclusive: false,
									 autoDelete: false,
									 arguments: null);

				var consumer = new EventingBasicConsumer(channel);
				consumer.Received += (model, ea) =>
				{
					var body = ea.Body.ToArray();
					var message = Encoding.UTF8.GetString(body);
					Console.WriteLine(" [x] Received {0}", message);
				};
				channel.BasicConsume(queue: "cap.queue.keep.api.v1",
									 autoAck: true,
									 consumer: consumer);

				Console.WriteLine(" [*] Waiting for messages. To exit press CTRL+C");
				Console.ReadLine();
			}



		}
	}
}
